package cn.bonoon.kernel.support;

import javax.persistence.EntityManager;

import cn.bonoon.kernel.exceptions.UniqueCheckException;

public final class UniqueChecker{
	private final String errorMsg, exist;
	public UniqueChecker(String entityName, String propertyName, String errorMsg){
		this.exist = "select count(x.id) from " + entityName + " x where x." + propertyName + "=? and x.id<>?";
		this.errorMsg = errorMsg;
	}
	public void check(EntityManager entityManager, Long id, String newValue) {
		if(id == null) id = -1L;
		if(entityManager.createQuery(exist, Number.class)
				.setParameter(1, newValue)
				.setParameter(2, id)
				.getSingleResult().intValue() > 0){
			throw new UniqueCheckException(String.format(errorMsg, newValue));
		}
	}
	
	public void check(EntityManager entityManager, Long id, String newValue, String limitProperty, Object limitValue) {
		if(id == null) id = -1L;		
		if(entityManager.createQuery(exist + " and x." + limitProperty + "=?", Number.class)
				.setParameter(1, newValue)
				.setParameter(2, id)
				.setParameter(3, limitValue)
				.getSingleResult().intValue() > 0){
			throw new UniqueCheckException(String.format(errorMsg, newValue));
		}
	}
}
